package com.hcb.tonguetiphealth.widget.healthShare;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.HealthShareListAdapter;
import com.hcb.tonguetiphealth.adapter.ResListAdapter;
import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.DBManager;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.HealthShare;
import com.hcb.tonguetiphealth.model.ResDish;
import com.hcb.tonguetiphealth.model.Restaurant;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.DIYActivity;
import com.hcb.tonguetiphealth.view.DrinksBookActivity;
import com.hcb.tonguetiphealth.view.LoginActivity;
import com.hcb.tonguetiphealth.view.MoreActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.view.RecommendHealthActivity;
import com.hcb.tonguetiphealth.view.ResBookActivity;
import com.hcb.tonguetiphealth.view.SearchActivity;
import com.hcb.tonguetiphealth.widget.BottomWidget;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class HealthShareWidget extends GeneralWidget implements OnClickListener {
	
	private Activity ctx;

	private Handler mHandler;
	private LinearLayout llBack, llDiy;
	private User user;
	private List<HealthShare>healthShareList ;
	private ListView healthShareListView;

	private String userName="-1";
	private String count = "0";
	
	private HealthShareListAdapter adapter;
	private View footerView;
	private TextView tv_footerMore;
	private ProgressBar pb_footerMore;
	private String keyWord;
	
	public HealthShareWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.health_share, this); 
	//	new BottomWidget(context, this);
		userName = ctx.getIntent().getStringExtra("userName");
		if (userName == null) {
			userName = "-1";
		} 
		keyWord = ctx.getIntent().getStringExtra("keyword");
		bindView();
		bindEvent();
		
		healthShareList = new ArrayList<HealthShare>();
		adapter = new HealthShareListAdapter(ctx, healthShareList);
		adapter.setKeyword(keyWord);
		healthShareListView.setAdapter(adapter);
		Calendar calendar = Calendar.getInstance();
		long now = calendar.getTimeInMillis();// 获得当前时间的毫秒表示
		calendar.set(2013, 4, 27, 0, 0, 0);
		long end = calendar.getTimeInMillis();
		if (now < end) {
			getHealthShareList();
		}
	}
	
	private void bindView(){
		
		llBack = (LinearLayout)findViewById(R.id.healthshare_linearlayout_back);
		footerView = LayoutInflater.from(ctx).inflate(R.layout.refresh_list_footer, null);
		healthShareListView = (ListView)findViewById(R.id.health_share_listview);
		tv_footerMore = (TextView)footerView.findViewById(R.id.refresh_list_footer_text);
		pb_footerMore = (ProgressBar)footerView.findViewById(R.id.refresh_list_footer_progressbar);
		healthShareListView.addFooterView(footerView);
		llDiy = (LinearLayout)findViewById(R.id.health_share_diy_ll);
	}
	
	private void bindEvent(){
		llBack.setOnClickListener(this);
		llDiy.setOnClickListener(this);
		footerView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				tv_footerMore.setText(R.string.app_list_footer_getting_text);
				pb_footerMore.setVisibility(ProgressBar.VISIBLE);
				getHealthShareList();
			}
		});
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取传递列表...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					adapter.notifyDataSetChanged();
					tv_footerMore.setText(R.string.app_list_footer_more_text);
					pb_footerMore.setVisibility(ProgressBar.GONE);
					dismissMessageDialog();
					break;
				 
				case MessageWhat.NETWORK_FAILD:
					try {
					  tv_footerMore.setText(R.string.app_list_footer_more_text);
					  pb_footerMore.setVisibility(ProgressBar.GONE);
					  dismissMessageDialog();
					} catch (Exception e) {
						// TODO: handle exception
					}
					//Toast.makeText(ctx,  "网络有点不给力哦", Toast.LENGTH_LONG).show();
					showMessage(ctx, R.string.net_faild);
					break;
				}
			}
		};
	}
	
	
	/**
	 * 底部功能菜单按钮点击事件
	 */
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.healthshare_linearlayout_back:
			ctx.finish();
			break;
		case R.id.health_share_diy_ll:
			ctx.startActivity(new Intent(ctx, DIYActivity.class));
			ctx.finish();
			break;
		default:
			break;
		}
	}
	
	 
	private void getHealthShareList(){
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		count = healthShareList.size()+"";
		new Thread(){
			public void run() {
				List <NameValuePair> params = new ArrayList <NameValuePair>();
				String response = null;
				System.out.println("count-------------"+count);
				if (keyWord != null) {
					params.add(new BasicNameValuePair("keyword", keyWord));
					params.add(new BasicNameValuePair("count", count));
					response = HttpUtils.Post(Global.getServlethealthsharesearch(), params);
				}else {
					params.add(new BasicNameValuePair("buyer", userName));
					params.add(new BasicNameValuePair("count", count));
					response = HttpUtils.Post(Global.getServlethealtshare(), params);
				}
				
				
				if (Global.DEBUG) {
					System.out.println("response" + response);
				}
				if (response!=null) {
					parseResponse(response);
					mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
				}else {
					mHandler.sendEmptyMessage(MessageWhat.NETWORK_FAILD);
				}
			}
		}.start();
	}
	
	//解析返回的结果（json）
	private void parseResponse(String result){
		JSONManager jsonManager = new JSONManager();
		boolean success = jsonManager.isGotJSONObject(result);
		if (success) {
			JSONArray jsonArray = jsonManager.getJsonList();
			for(int i=0; jsonArray != null  && i < jsonArray.length(); i++) {
				try {
					HealthShare healthShare = new HealthShare();
					JSONObject obj = jsonArray.getJSONObject(i);
					
					//查询时返回格式不一致
					if (keyWord!=null) {
						healthShare.setItemId(obj.getString("itemid"));
						healthShare.setDiyImg(obj.getString("img"));
						User user = new User();
						user.setUserId(obj.getString("userid"));
						user.setUserName(obj.getString("username"));
						user.setImgUrl(obj.getString("headicon"));
						user.setCommentNum(obj
								.getString("commentNumber"));
						user.setLevel(StringUtils.parseFloat(obj
								.getString("level")));
						healthShare.setUser(user);
						healthShare.setContent(obj.getString("content"));
						healthShare.setContentId(obj.getString("itemid"));
						healthShare.setType("4");
					}else {
						healthShare.setType(obj.getString("type"));
						if ("1".equals(healthShare.getType())) {
							healthShare.setItemId(obj.getString("itemid"));
							healthShare.setFlower(StringUtils.parseInt( obj.getString("flower") ));
							healthShare.setShare(StringUtils.parseInt( obj.getString("share") ));
							healthShare.setUser(parseUser(obj.getJSONObject("buyers")));
							healthShare.setRes(parseRes(obj.getJSONObject("sellers")));
							healthShare.setContentId(obj.getString("itemoid"));
							healthShare.setDishList(parseDishList(obj.getJSONArray("orderinfo")));;
						}else {
							healthShare.setItemId(obj.getString("itemid"));
							healthShare.setFlower(StringUtils.parseInt( getString(obj, "flower") ));
							healthShare.setFlower(StringUtils.parseInt( getString(obj, "share") ));
							healthShare.setDiyImg(obj.getString("img"));
							healthShare.setUser(parseUser(obj.getJSONObject("buyers")));
							healthShare.setContent(obj.getString("content"));
							healthShare.setContentId(obj.getString("itemid"));	
							}
						
					}
						
					healthShareList.add(healthShare);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public void notifyAdapter() {
		
	}

	private User parseUser(JSONObject jsonObject) {
		User user = new User();
		try {
			user.setUserId(jsonObject.getString("userid"));
			user.setUserName(jsonObject.getString("username"));
			user.setImgUrl(jsonObject.getString("headicon"));
			user.setCommentNum(jsonObject.getString("commentNumber"));
			user.setLevel(StringUtils.parseFloat(jsonObject.getString("level")));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Log.e("HealthShareWidgrt", "解析用户信息", e);
		}

		return user;
	}
	
	private Restaurant parseRes(JSONObject jsonObject) {
		Restaurant res = new Restaurant();
		try {
			res.setId(jsonObject.getString("userid"));;
			res.setName(jsonObject.getString("company"));
			res.setImgURL(jsonObject.getString("thumb"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Log.e("HealthShareWidgrt", "解析商户信息", e);
		}

		return res;
	}
	
	private List<ResDish> parseDishList(JSONArray jsonArray) {
		List<ResDish> dishList = new ArrayList<ResDish>();
		try {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject obj = jsonArray.getJSONObject(i);
				ResDish dish = new ResDish();
				dish.setTitle(obj.getString("title"));
				dish.setNum(obj.getString("number"));
				dish.setDishThumb(obj.getString("thumb"));
				dishList.add(dish);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			Log.e("HealthShareWidgrt", "解析菜品信息", e);
		}

		return dishList;
	}
	
}
